/**    
* 写这段代码的时候，只有上帝和我知道它是干嘛的
* 现在，只有上帝知道
*/
using UnityEngine;
//using System.Collections;
using System.IO;
using System;

/// <summary>
/// 写文件
/// </summary>
public class WriteLog
{

    private string m_infoFile;
 
    private static readonly object s_lock = new object();
    private static WriteLog s_instance;
    public static WriteLog instance
    {
        get
        {
            if (s_instance == null)
            {
                lock (s_lock)
                {
                    if (s_instance == null)
                    {
                        s_instance = new WriteLog();
                    }
                }
            }
            return s_instance;
        }
    }
 
    private WriteLog()
    {
        Init();
    }
 
    private void Init()
    {
#if UNITY_EDITOR
        string dir = Application.dataPath;
        int index = dir.LastIndexOf("/");
        dir = dir.Substring(0, index);
        dir += "/GameLog";
        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
        m_infoFile = dir + "/" + "gamelog.txt";
#else
        string dir = string.Format("{0}/{1}", Application.dataPath, "GameLog");
        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
        m_infoFile = dir + "/" + "gamelog.txt";
#endif
    }

    /// <summary>
    /// 获取调用堆栈信息
    /// </summary>
    private string GetStackTrace()
    {
        System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(true);
        string stackIndent = "";
        for (int i = 0; i < st.FrameCount; i++)
        {
            System.Diagnostics.StackFrame sf = st.GetFrame(i);
 
            //得到错误的方法
            stackIndent += sf.GetMethod() + "";
            //得到错误的文件名
           // stackIndent += sf.GetFileName() + "";
            //得到文件错误的行号
            //stackIndent += (":" + sf.GetFileLineNumber()) + "";
            //得到错误的列
            //stackIndent += " column:" + sf.GetFileColumnNumber() + " ";
            stackIndent += DateTime.Now+"";

            stackIndent += "\n";
        }
        return stackIndent;
    }
 
    /// <summary>
    /// 写入信息到本地文件
    /// </summary>
    /// <param name="info">信息</param>
    public void WriteInfo(string info)
    {
        using (StreamWriter sw = File.AppendText(m_infoFile))
        {
            //string stackInfo = new System.Diagnostics.StackTrace().ToString();
            // string stackInfo = GetStackTrace();
            info += ("\n" + DateTime.Now);
            sw.WriteLine(info);
        }
    }
}
